<?php
/**
 * Created by PhpStorm.
 * User: Mysic
 * Date: 2020/10/21
 * Time: 16:43
 */

namespace app\admin\controller\fix;

use app\admin\controller\Controller;
use app\admin\service\fix\BonusFix;
use think\Request;
use app\common\library\MysicLog;

class Bonus extends Controller
{
    const FIX_TYPE_BONUS = 2;
    protected $log;
    protected $bonusFix;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->log = MysicLog::instance();

    }

    public function query()
    {
        $orderNo = $this->request->get('order_no');
        $list = db('fix_log')->where('order_no', $orderNo)->where('type', self::FIX_TYPE_BONUS)->select();
        return $this->renderSuccess('查询完毕', '', $list);
    }

    public function index()
    {
        if(!$this->request->isPost()){
            return $this->fetch('index');
        }

        $orderNo = $this->request->post('order_no');
        try {
            $this->bonusFix = new BonusFix($orderNo);
        } catch(\Exception $e) {
            return $this->renderError($e->getMessage());
        }
        $ops = $this->request->post('op/a');

        if(empty($ops)) {
            return $this->renderError('没有选择要执行逻辑');
        }
        $executed = [];
        $error = '';
        foreach($ops as $k => $executeOp) {
            $ret = $this->bonusFix->{$executeOp}();
            if(!$ret->getStatus()){
                $error = $ret->getMsg();
                break;
            }
            $executed[] = [
                'order_no' => $orderNo,
                'type' => self::FIX_TYPE_BONUS,
                'process' => $executeOp,
                'create_time' => time()
            ];
        }
        if(!empty($executed)) {
            db('fix_log')->insertAll($executed);
        }
        if($error) {
            return $this->renderError($error);
        }
        return $this->renderSuccess('执行完毕');
    }
}